<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合约名称" prop="contractName">
        <el-input v-model="queryParams.contractName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" maxlength="27"/>
      </el-form-item>
      <el-form-item label="公司" prop="companyId">
        <el-select v-model="queryParams.companyId" clearable @change="handleQuery">
          <el-option v-for="item in companyList" :key="item.companyId" :label="item.companyName"
            :value="item.companyId" />
        </el-select>
      </el-form-item>
      <el-form-item label="医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" clearable @change="handleQuery">
          <el-option v-for="item in hospitalList" :key="item.hospitalId" :label="item.name" :value="item.hospitalId" />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="departmentId">
        <el-select v-model="queryParams.departmentId" clearable @change="handleQuery">
          <el-option v-for="item in departmentList" :key="item.departmentId" :value="item.departmentId"
            :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable @change="handleQuery">
          <el-option v-for="item in CONTRACT_STATUS" :key="item.value" :value="item.value" :label="item.label"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['basic:contract:add']">添加合约</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="!disabledMultiple" @click="handleDelete"
          v-hasPermi="['basic:contract:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="dynamicHeightTable" :max-height="tableMaxHeight - 84" v-loading="loading" :data="contractList"
      @selection-change="handleSelectionChange">

      <el-table-column label="序号" width="55" align="center">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合约名称" align="center" prop="contractName" />
      <el-table-column label="合约编号" align="center" prop="contractNo" />
      <el-table-column label="公司" align="center" prop="companyName" />
      <el-table-column label="医院" align="center" prop="hospitalName" />
      <el-table-column label="科室" align="center" prop="departmentName" />
      <el-table-column label="合约生效日期" align="center" prop="effectiveDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合约失效日期" align="center" prop="expirationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="{row}">
          <dict-tag :options="CONTRACT_STATUS" :value="row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" >
        <template v-slot="{row}">{{labelNickName(row.createBy)}}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:contract:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['basic:contract:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合约名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入" maxlength="27" />
        </el-form-item>
        <el-form-item label="合约编号" prop="contractNo" >
          <el-input v-model="form.contractNo" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="公司" prop="companyId">
          <el-select v-model="form.companyId" clearable >
            <el-option v-for="item in companyOptionList" :key="item.companyId" :label="item.companyName"
              :value="item.companyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" clearable @change="dialogHospitalChange" >
            <el-option v-for="item in hospitalList" :key="item.hospitalId" :label="item.name" :value="item.hospitalId" />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentIds">
          <el-select v-model="middlewareDepartmentIds" clearable multiple >
            <el-option value="">
              <span @click="middlewareDepartmentIdsSelectedAll = !middlewareDepartmentIdsSelectedAll">
                {{ middlewareDepartmentIdsSelectedAll ? '清空' : '全选' }}
              </span>
            </el-option>
            <el-option v-for="item in departmentList" :key="item.departmentId" :value="item.departmentId" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效日期" prop="effectiveDate">
          <el-date-picker clearable v-model="form.effectiveDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期" prop="expirationDate">
          <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
} from "@/api/basic/contract";
import { optionHospitalNoLimit } from "@/api/hospital/hospital";
import { optionDepartmentNoLimit } from "@/api/hospital/department";
import tableMaxHeightRefresh from "@/mixins/tableMaxHeightRefresh";
import {optionCompany, selectionCompany} from "@/api/basic/company";
import { nickName } from '@/mixins/nickName'

const CONTRACT_STATUS = [
  {value: '0', label: '未生效', raw: {listClass: 'info'}},
  {value: '1', label: '已生效', raw: {listClass: 'success'}},
  {value: '2', label: '已失效', raw: {listClass: 'warning'}},
]

export default {
  name: "Contract",
  mixins: [nickName('contractList'),tableMaxHeightRefresh],
  data () {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      disabledMultiple: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医院列表
      hospitalList: [],
      // 科室列表
      departmentList: [],
      // 公司列表(所有合同)
      companyList: [],
      // 公司列表(生效合同)
      companyOptionList: [],
      // 合同表表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: undefined,
        hospitalId: undefined,
        departmentId: undefined,
        contractName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractName: [
          { required: true, message: "合约名称不能为空", trigger: "blur" },
        ],
        contractNo: [
          { required: true, message: "合约编号不能为空", trigger: "blur" },
        ],
        companyId: [
          { required: true, message: "公司不能为空", trigger: "change" },
        ],
        hospitalId: [
          { required: true, message: "医院不能为空", trigger: "change" },
        ],
        departmentIds: [
          { required: true, message: "科室不能为空", trigger: "change" },
        ],
        effectiveDate: [
          { required: true, message: "合约生效日期不能为空", trigger: "blur" },
        ],
        expirationDate: [
          { required: true, message: "合约失效日期不能为空", trigger: "blur" },
          {
              validator: (rules, value, callback) => {
                if (value) {
                  const startDate = new Date(this.form.effectiveDate)?.getTime()
                  const endDate = new Date(value)?.getTime()
                  if (startDate && endDate && endDate < startDate)  return callback(new Error(rules.message))
                }
                callback()
              },
              message: '失效日期需要≥生效日期',
              trigger: "blur"
            }
        ],
      },
    };
  },
  watch: {
    "queryParams.hospitalId": {
      handler (newValue, oldValue) {
        this.queryParams.departmentId = "";
        this.departmentList = [];
        if (newValue) {
          this.getAllDepartment(newValue)
        }
      },
      immediate: true,
    }
  },
  computed:{
    CONTRACT_STATUS() {return CONTRACT_STATUS},
    middlewareDepartmentIds: {
      get() {
        return typeof this.form.departmentIds === 'string'
          ? this.form.departmentIds.split(',').filter(item => !!item)
          : []
      },
      set(val) {
        if (Array.isArray(val) && val.every(item => typeof item === 'string')) {
          this.form.departmentIds = val.filter(item => !!item).join(',')
        } else {
          this.form.departmentIds = ''
        }
      }
    },
    middlewareDepartmentIdsSelectedAll: {
      get() {
        return this.departmentList.length && this.middlewareDepartmentIds.length === this.departmentList.length;
      },
      set(val) {
        if (val) {
          this.middlewareDepartmentIds = this.departmentList.map(item => item.departmentId)
        } else {
          this.middlewareDepartmentIds = []
        }
      }
    }
  },
  created () {
    this.getList();
    this.getAllListHospital();
    this.getAllCompany();
    this.getOptionCompany();
  },
  methods: {
    asd() {
      console.log(123)
    },
    /** 弹框 医院id选择框变化 */
    dialogHospitalChange(){
      this.form.departmentIds = ''
      this.departmentList = []
      if (this.form.hospitalId) {
        this.getAllDepartment(this.form.hospitalId)
      }
    },
    /** 查询医院列表 */
    getAllListHospital () {
      return optionHospitalNoLimit().then(response => {
        this.hospitalList = response.data
        return Promise.resolve(response)
      });
    },
    /** 查询科室列表 */
    getAllDepartment (hospitalId) {
      return optionDepartmentNoLimit({hospitalId}).then(response => {
          this.departmentList = response.data
          return Promise.resolve(response)
        }
      );
    },
    /** 查询公司列表 */
    getAllCompany () {
      return selectionCompany().then(response => {
        this.companyList = response.data
        return Promise.resolve(response)
      });
    },
    getOptionCompany() {
      return optionCompany().then(response => {
        this.companyOptionList = response.data
        return Promise.resolve(response)
      });
    },
    /** 查询合约表列表 */
    getList () {
      this.loading = true;
      return listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
        return Promise.resolve(response)
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        departmentIds: '',
        companyId: undefined,
        hospitalId: undefined,
        contractName: undefined,
        contractNo: undefined,
        effectiveDate: undefined,
      };
      this.departmentList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.contractId);
      this.disabledMultiple = selection.length > 1
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加合约";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const contractId = row.contractId || this.ids;
      this.getAllDepartment(row.hospitalId)
      getContract(contractId).then((response) => {
        this.loading = false;
        const form = {
          ...response.data,
        }
        this.form = form
        this.open = true;
        this.title = "修改合约";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        const form = {
          companyId:this.form.companyId,
          contractId:this.form.contractId,
          contractName:this.form.contractName,
          contractNo:this.form.contractNo,
          departmentIds:this.form.departmentIds,
          effectiveDate:this.form.effectiveDate,
          expirationDate:this.form.expirationDate,
          hospitalId:this.form.hospitalId,
        }
        if (valid) {
          this.buttonLoading = true;
          if (this.form.contractId != null) {
            updateContract(form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.departmentList = []
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addContract(form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.departmentList = []
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const contractIds = row.contractId || this.ids;
      const tips = row.contractId ? '确认删除该合约吗？' : '确认删除所选择的合约吗？'
      this.$modal.confirm(tips)
        .then(() => {
          this.loading = true;
          return delContract(contractIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
